from urllib.parse import urljoin
import requests

class APIClient:
    def __init__(self, protocol, host):
        """
        初始化 APIClient
        :param protocol: 请求协议（http or https）
        :param base_url: 基础url地址（例如 httpbin.org）
        """
        self.protocol = protocol
        self.host = host

        self.default_headers = {
            "Accept": "application/json",
            "Content-Type": "application/json"
        }

        # 根据协议和环境配置生成base_url
        self.base_url = f"{self.protocol}://{self.host}"
        self.headers = {"Accept": "application/json", "Content-Type": "application/json"}

    def _send_request(self, method, endpoint, headers=None, **kwargs):
        """
        通用请求方法
        :param method: 请求方法 (GET/POST/PUT/PATCH/DELETE)
        :param endpoint: 请求路径 (例如 "/anything")
        :param kwargs: 传递给 requests 请求的其他参数
        :return: 响应对象
        """
        url = urljoin(self.base_url, endpoint)  # 将 base_url 和 endpoint 拼接成完整的 URL
        if headers:
            self.default_headers.update(headers)
        else:
            headers = self.default_headers
        response = requests.request(method, url, headers=headers, **kwargs)
        return response

    def get(self, endpoint, headers=None, **kwargs):
        """发送 GET 请求"""
        return self._send_request("GET", endpoint, headers, **kwargs)

    def post(self, endpoint, headers=None, **kwargs):
        """发送 POST 请求"""
        return self._send_request("POST", endpoint, headers, **kwargs)

    def put(self, endpoint, headers=None, **kwargs):
        """发送 PUT 请求"""
        return self._send_request("PUT", endpoint, headers, **kwargs)

    def patch(self, endpoint, headers=None, **kwargs):
        """发送 PATCH 请求"""
        return self._send_request("PATCH", endpoint, headers, **kwargs)

    def delete(self, endpoint, headers=None, **kwargs):
        """发送 DELETE 请求"""
        return self._send_request("DELETE", endpoint, headers, **kwargs)